package com.powernode.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.shop.constant.CategoryConstant;
import com.powernode.shop.domain.Category;
import com.powernode.shop.mapper.CategoryMapper;
import com.powernode.shop.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
/**
* @author ZHAOZHENYU
* @since 2022/10/12
*/
@CacheConfig(cacheNames = "com.powernode.shop.service.impl.CategoryServiceImpl")    // 抽取缓存方法的公共属性
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Cacheable(key = CategoryConstant.CATEGORY_LIST)    // 结果放入缓存
    @Override
    public List<Category> getCategoryList() {
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>().orderByDesc(Category::getSeq));
    }

    @Override
    public List<Category> selectParentCategoryList() {
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, 0)
                .eq(Category::getStatus, 1)
                .orderByDesc(Category::getSeq));
    }

    @Caching(evict = {@CacheEvict(CategoryConstant.CATEGORY_LIST),
            @CacheEvict(CategoryConstant.CATEGORY_PARENT_LIST)})
    @Override
    public boolean save(Category category) {

        Long parentId = category.getParentId();
        if (parentId == null || parentId == 0L) {    // 一级分类
            category.setParentId(0L);
            category.setGrade(1);
        }else { // 不是一级分类
            Category parent = categoryMapper.selectById(parentId);
            if(ObjectUtils.isEmpty(parent)){
                throw new IllegalArgumentException("新增分类，父类不能为空");
            }
            category.setGrade(2);
        }
        category.setRecTime(new Date());
        category.setShopId(1L);
        int insert = categoryMapper.insert(category);
        return insert > 0;
    }

}
